/*
 * Copyright 2007-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.paoding.rose.web.var;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import net.paoding.rose.impl.util.PlaceHolderUtils;
import net.paoding.rose.web.Invocation;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.Conventions;
import org.springframework.util.Assert;

/**
 * 
 * @author qieqie.wang@paoding.net
 * 
 */
public class ModelImpl implements Model {

	private static Log logger = LogFactory.getLog(ModelImpl.class);

	private LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
	
	private Invocation invocation;
	
	public ModelImpl(Invocation invocation) {
		this.invocation = invocation;
	}

	public Map<String, Object> getAttributes() {
		return Collections.unmodifiableMap(map);
	}

	@Override
	public Model add(String name, Object value) {
		Assert.notNull(name, "Model attribute name must not be null");
		if (value instanceof String) {
			value = PlaceHolderUtils.resolve((String) value, invocation);
		}
		map.put(name, value);
		if (logger.isDebugEnabled()) {
			logger.debug("add attribute to model: " + name + "=" + value);
		}

		return this;
	}

	@Override
	public Model add(Object value) {
		if (value != null) {
			if (value instanceof Collection) {
				Collection<?> collection = (Collection<?>) value;
				if (collection.size() == 0) {
					return this;
				}
			}
			return add(Conventions.getVariableName(value), value);
		}
		return this;
	}

	@Override
	public boolean contains(String name) {
		return map.containsKey(name);
	}

	@Override
	public Object get(String name) {
		return map.get(name);
	}

	@Override
	@SuppressWarnings("unchecked")
	public Model merge(Map<?, ?> attributes) {
		if (attributes != null) {
			for (Iterator it = attributes.keySet().iterator(); it.hasNext();) {
				Object key = it.next();
				if (!contains(key.toString())) {
					add(key.toString(), attributes.get(key));
				}
			}
		}
		return this;
	}

	@Override
	public Model remove(String name) {
		if (name == null) {
			return this;
		}
		map.remove(name);
		return this;
	}

}
